import {ExceptionFilter, ArgumentsHost, HttpException, HttpStatus} from "@nestjs/common";
import {Response} from 'express'
export class GlobalHttpExceptionFilter implements ExceptionFilter {
    catch(exception: any,host: ArgumentsHost) {
        const ctx = host.switchToHttp();
        const response = ctx.getResponse<Response>();
        // 如果此相应已经发送完给客户端，不需要处理
        if(response.headersSent){
            return;
        }
        if(exception instanceof HttpException){
            if(typeof exception.getResponse() === 'string'){
                const status = exception.getStatus();
                response.status(status).json({
                    statusCode: status,
                    message: exception.getResponse(),
                })
            }else{
                response.status(exception.getStatus()).json(exception.getResponse())
            }
        }else{
            return response.status(500).json({
                statusCode:HttpStatus.INTERNAL_SERVER_ERROR,
                error:exception.message,
                message: 'Internal Server Error',
            })
        }
    }
}
